<template>
  <div class="bar-chart">
    <div class="title">
      {{ barTitle }}
    </div>
    <div class="chart" ref="BarChartDom"></div>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, onMounted, watch } from 'vue'
const props = defineProps({
  barData: {
    type: Array,
    default: () => []
  },
  barTitle: {
    type: String,
    default: '卫星状态图'
  },
  isEffect: {
    type: Boolean,
    default: false
  }
})
const BarChartDom = ref(null)
const { proxy } = getCurrentInstance()
const option = reactive({
  tooltip: {
    trigger: 'axis',
    backgroundColor: '#666',
    borderColor: '#666',
    textStyle: {
      color: '#fff'
    },
    axisPointer: {
      type: 'shadow'
    },
    formatter: function (params) {
      let res = ''
      res = `<div>
          <div style="color: #fff; text-align:center">${params[0].marker} ${params[0].name}</div>
          <div style="color: #01E4F8; font-weight: 650">${props.isEffect ? '效能等级' : '健康状态'}
            <span style="color: ${params[0].data.itemStyle?.color}"> ${params[0].data.levelName || '暂无数据'} </span>
          </div>
          <div style="color: #01E4F8; font-weight: 650">${props.isEffect ? '效能指数' : '健康指数'}
            <span style="color: ${params[0].data.itemStyle?.color}"> ${params[0].data.score || '暂无数据'} </span>
          </div>
        </div>`
      return res
    }
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      show: true,
      color: '#ffffff'
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      show: true,
      color: '#ffffff'
    }
  },
  series: [
    {
      data: [],
      type: 'bar',
      name: '数量'
    }
  ]
})
let BarChart = null
const initChart = () => {
  BarChart = proxy.$echarts.init(BarChartDom.value)
  updateOption(option)
}
const updateOption = (option) => {
  const BarXdata = reactive([])
  const BarYdata = reactive([])
  props.barData.forEach((item) => {
    BarXdata.push(item.name)
    BarYdata.push(item.value)
  })
  option.xAxis.data = BarXdata
  option.series[0].data = BarYdata
  BarChart?.setOption(option)
}
watch(
  () => props.barData,
  () => {
    updateOption(option)
  }
)
onMounted(() => {
  initChart()
})
</script>

<style lang="less" scoped>
.bar-chart {
  width: 100%;
  height: 300px;
  color: #fff;
  background: url('@/assets/image/chart-bg.png') no-repeat;
  background-size: 100% 100%;
  display: flex;
  flex-direction: column;
  .title {
    height: 40px;
    line-height: 40px;
    font-size: 18px;
    font-weight: 650;
    color: #01e4f8;
    text-align: center;
  }
  .chart {
    flex: 1;
  }
}
</style>
